package org.example.ding.controller;

import jakarta.validation.Valid;
import org.example.ding.dto.DishCategoryDto;
import org.example.ding.entity.DishCategory;
import org.example.ding.service.DishCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜品分类管理控制器
 */
@Controller
@RequestMapping("/admin/categories")
public class DishCategoryController {

    @Autowired
    private DishCategoryService dishCategoryService;

    /**
     * 分类列表页面
     */
    @GetMapping
    public String listCategories(Model model) {
        List<DishCategoryDto> categories = dishCategoryService.getAllCategoryDtos();
        List<DishCategoryService.CategoryWithCount> categoriesWithCount = 
            dishCategoryService.getCategoriesWithDishCount();
        
        model.addAttribute("categories", categories);
        model.addAttribute("categoriesWithCount", categoriesWithCount);
        
        return "admin/categories/list";
    }

    /**
     * 显示创建分类页面
     */
    @GetMapping("/create")
    public String showCreateForm(Model model) {
        model.addAttribute("categoryDto", new DishCategoryDto());
        model.addAttribute("mealTypes", DishCategory.MealType.values());
        return "admin/categories/create";
    }

    /**
     * 处理创建分类
     */
    @PostMapping("/create")
    public String createCategory(@Valid @ModelAttribute("categoryDto") DishCategoryDto categoryDto,
                                BindingResult result,
                                Model model,
                                RedirectAttributes redirectAttributes) {
        
        if (result.hasErrors()) {
            model.addAttribute("mealTypes", DishCategory.MealType.values());
            return "admin/categories/create";
        }

        try {
            DishCategory category = dishCategoryService.createCategory(categoryDto);
            redirectAttributes.addFlashAttribute("successMessage", 
                "分类 \"" + category.getName() + "\" 创建成功！");
            return "redirect:/admin/categories";
        } catch (RuntimeException e) {
            result.rejectValue("name", "error.categoryDto", e.getMessage());
            model.addAttribute("mealTypes", DishCategory.MealType.values());
            return "admin/categories/create";
        }
    }

    /**
     * 显示编辑分类页面
     */
    @GetMapping("/{id}/edit")
    public String showEditForm(@PathVariable Long id, Model model) {
        DishCategory category = dishCategoryService.findById(id)
            .orElseThrow(() -> new RuntimeException("分类不存在"));
        
        DishCategoryDto categoryDto = DishCategoryDto.fromDishCategory(category);
        
        model.addAttribute("categoryDto", categoryDto);
        model.addAttribute("mealTypes", DishCategory.MealType.values());
        
        return "admin/categories/edit";
    }

    /**
     * 处理编辑分类
     */
    @PostMapping("/{id}/edit")
    public String editCategory(@PathVariable Long id,
                              @Valid @ModelAttribute("categoryDto") DishCategoryDto categoryDto,
                              BindingResult result,
                              Model model,
                              RedirectAttributes redirectAttributes) {
        
        if (result.hasErrors()) {
            model.addAttribute("mealTypes", DishCategory.MealType.values());
            return "admin/categories/edit";
        }

        try {
            DishCategory category = dishCategoryService.updateCategory(id, categoryDto);
            redirectAttributes.addFlashAttribute("successMessage", 
                "分类 \"" + category.getName() + "\" 更新成功！");
            return "redirect:/admin/categories";
        } catch (RuntimeException e) {
            result.rejectValue("name", "error.categoryDto", e.getMessage());
            model.addAttribute("mealTypes", DishCategory.MealType.values());
            return "admin/categories/edit";
        }
    }

    /**
     * 查看分类详情
     */
    @GetMapping("/{id}")
    public String viewCategory(@PathVariable Long id, Model model) {
        DishCategory category = dishCategoryService.findById(id)
            .orElseThrow(() -> new RuntimeException("分类不存在"));
        
        DishCategoryDto categoryDto = DishCategoryDto.fromDishCategory(category);
        model.addAttribute("categoryDto", categoryDto);
        
        return "admin/categories/view";
    }

    /**
     * 删除分类
     */
    @PostMapping("/{id}/delete")
    public String deleteCategory(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            DishCategory category = dishCategoryService.findById(id)
                .orElseThrow(() -> new RuntimeException("分类不存在"));
            
            dishCategoryService.deleteCategory(id);
            redirectAttributes.addFlashAttribute("successMessage", 
                "分类 \"" + category.getName() + "\" 已删除！");
        } catch (RuntimeException e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
        }
        
        return "redirect:/admin/categories";
    }

    /**
     * 检查分类名称是否可用 (AJAX)
     */
    @GetMapping("/api/check-name")
    @ResponseBody
    public ResponseEntity<Map<String, Boolean>> checkCategoryName(@RequestParam String name,
                                                                 @RequestParam(required = false) Long excludeId) {
        boolean available;
        if (excludeId != null) {
            available = dishCategoryService.isCategoryNameAvailable(name, excludeId);
        } else {
            available = dishCategoryService.isCategoryNameAvailable(name);
        }
        
        Map<String, Boolean> response = new HashMap<>();
        response.put("available", available);
        return ResponseEntity.ok(response);
    }

    /**
     * 根据餐别类型获取分类 (AJAX)
     */
    @GetMapping("/api/by-meal-type")
    @ResponseBody
    public ResponseEntity<List<DishCategoryDto>> getCategoriesByMealType(@RequestParam String mealType) {
        try {
            DishCategory.MealType mealTypeEnum = DishCategory.MealType.valueOf(mealType);
            List<DishCategoryDto> categories = dishCategoryService.getCategoryDtosByMealType(mealTypeEnum);
            return ResponseEntity.ok(categories);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 获取所有分类 (AJAX)
     */
    @GetMapping("/api/all")
    @ResponseBody
    public ResponseEntity<List<DishCategoryDto>> getAllCategories() {
        List<DishCategoryDto> categories = dishCategoryService.getAllCategoryDtos();
        return ResponseEntity.ok(categories);
    }

    /**
     * 获取分类统计信息 (AJAX)
     */
    @GetMapping("/api/statistics")
    @ResponseBody
    public ResponseEntity<List<DishCategoryService.CategoryWithCount>> getCategoryStatistics() {
        List<DishCategoryService.CategoryWithCount> stats = dishCategoryService.getCategoriesWithDishCount();
        return ResponseEntity.ok(stats);
    }

    /**
     * 初始化默认分类
     */
    @PostMapping("/api/initialize")
    @ResponseBody
    public ResponseEntity<Map<String, String>> initializeDefaultCategories() {
        try {
            dishCategoryService.initializeDefaultCategories();
            Map<String, String> response = new HashMap<>();
            response.put("message", "默认分类初始化成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("error", "初始化失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}
